<template>
    <div class = "editarticle">
         <el-container style="height:100%">
            <el-container>
            <el-main  v-loading = "loading">
                 <el-breadcrumb separator="/" style="padding-bottom:15px;">
                <el-breadcrumb-item style="font-weight: bold;cursor:pointer" @click.native = "goBack">资讯管理</el-breadcrumb-item>
                <el-breadcrumb-item>{{Top}}</el-breadcrumb-item>
                </el-breadcrumb>
            <el-form :model="ruleForm" status-icon :rules="rules" ref="ruleForm"  style="100%;" label-width="80px" label-style="text-align: center;">
                        <el-form-item label="标题" prop = "title" >
                            <el-input v-model="ruleForm.title" autocomplete="off" placeholder="请输入标题"></el-input>
                        </el-form-item>
                        <el-form-item label="简述" prop = "desc">
                             <el-input
                                type="textarea"
                                :rows="4"
                                placeholder="请输入内容"
                                v-model="ruleForm.desc">
                                </el-input>
                        </el-form-item>
                        <el-form-item label="权重" prop = "weight">
                            <el-input type = "number" v-model="ruleForm.weight" placeholder="请输入权重"></el-input>
                        </el-form-item>
                        <el-form-item label="类型" prop = "type">
                            <el-select v-model="ruleForm.type" placeholder="请选择类型">
                            <el-option
                                v-for="item in options"
                                :key="item.label"
                                :label="item.label"
                                :value="item.value"
                            >
                            </el-option>
                            </el-select>
                        </el-form-item>
                        <el-form-item label="图片" >
                             <el-upload
                            :action="this.IP"
                            list-type="picture-card"
                            :data="{type:'image'}"
                            :limit="1"
                            :file-list="images"
                            :on-preview="handlePictureCardPreview"
                            :on-remove="handleRemove"
                            :on-success="handleAvatarSuccess">
                            <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog :visible.sync="dialogVisibleone">
                            <img width="100%" :src="ruleForm.imgId" alt="">
                            </el-dialog>
                        </el-form-item>
                        <el-form-item>
                         <quill-editor 
                        class="editor"
                        v-model="ruleForm.content"
                        ref="myQuillEditor" 
                        :options="editorOption" 
                        @blur="onEditorBlur($event)" 
                        @focus="onEditorFocus($event)"
                        @change="onEditorChange($event)">
                        </quill-editor>
                        </el-form-item>
                        <el-form-item>
                        <el-button v-if = "Boole === 0" style="float:right" type="primary" @click="submitForm('ruleForm')">提交</el-button>
                        <el-button v-if = "Boole === 1" style="float:right" type="primary" @click="submitFormone('ruleForm')">修改</el-button>
                        </el-form-item>
                        </el-form>
            </el-main>
            </el-container>
         </el-container>
    </div>
</template>
<script>
const toolbarOptions = [
          ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
		  ['blockquote', 'code-block'],
		  [{'header': 1}, {'header': 2}],               // custom button values
		  [{'list': 'ordered'}, {'list': 'bullet'}],
		  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
		  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
		  [{'direction': 'rtl'}],                         // text direction
		  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
		  [{'header': [1, 2, 3, 4, 5, 6, false]}],
		  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
		  [{'font': []}],
		  [{'align': []}],
		  ['link', 'image', 'video'],
		  ['clean']                                         // remove formatting button
];
import "quill/dist/quill.core.css";
import "quill/dist/quill.snow.css";
import "quill/dist/quill.bubble.css";
import articleshows from './articleshows'
export default {
    data(){
        var validatetitle = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入标题'));
        } else {
          callback();
        }
      };
      var validatedesc = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入简述'));
        } else {
          callback();
        }
      };
      var validatetype = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请选择类型'));
        } else {
          callback();
        }
      };
      var validateweight = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入权重'));
        } else {
          callback();
        }
      };
        return{
        compile:'',
        dialogVisibleone:false,
        Top:'',
        tableData:[],
        Boole:'',
        messageid:'',
        // 设置请求头
        options: [{
          value: 'research',
          label: '研学',
        }, {
          value: 'travel',
          label: '旅行'
        }],
        ruleForm: {
          title:'',
          content: ``,
          desc: ``,
          imgId:'',
          type:"",
          weight:''
        },
        rules:{
            title: [
                { validator: validatetitle, trigger: 'blur' }
            ],
            desc:[
                { validator: validatedesc, trigger: 'blur' }
            ],
            type:[
                { validator: validatetype, trigger: 'blur' }
            ],
            weight:[
                { validator: validateweight, trigger: 'blur' }
            ],
            },
        images:[],
        dialogVisible: false,
        loading: false,
          editorOption: {
              placeholder: '你想说点什么?',
              theme: 'snow',  // or 'bubble'
               modules: {
                        toolbar: {
                           container: toolbarOptions,  // 工具栏
                       },
                  }
            }
        }
    },
    components:{
        articleshows
    },
    created() {
        this.List()
    },
    methods:{
        List(){
            this.compile = this.$route.query.compile
            this.messageid = this.$route.query.form
            if(this.messageid){
                this.loading = true
                this.Top = '修改'
                this.Boole = 1
                this.$api.information.informationcompile(this.messageid).then(res => {
                   if(res.code === 200) {
                      this.ruleForm = res.data
                    if(res.data.image.url){
                        this.images = [{url:res.data.image.url}]
                    } else {
                        this.images = []
                    }
                    this.ruleForm.imgId = res.data.image.id 
                    this.loading = false
                   }
                }).catch(res => {
                    console.log(res)
                })
            } else {
                this.Boole = 0
                this.Top = '新增'
            }
        },
        handlePictureCardPreview(file){
            this.ruleForm.imgId = file.url;
            this.dialogVisibleone = true;
        },
        handleRemove(file, fileList) {
          this.ruleForm.imgId = ''
          this.images = []
        },
        handleAvatarSuccess(file) {
          this.ruleForm.imgId = file.data.id
        },
        onEditorReady(editor) {}, // 准备编辑器,
        onEditorBlur(){}, // 失去焦点事件
        onEditorFocus(){}, // 获得焦点事件
        onEditorChange(){}, // 内容改变事件
        //新增添加
        submitForm(formName){
            this.$refs[formName].validate((valid) => {
              if(this.ruleForm.imgId){
                if (valid) {
                  let Add = {
                        type:this.ruleForm.type,
                        title:this.ruleForm.title,
                        content:this.ruleForm.content,
                        desc:this.ruleForm.desc,
                        weight:this.ruleForm.weight,
                        imgId:this.ruleForm.imgId
                  }
                 this.$api.information.informationadd(Add).then(res => {
                     if(res.code === 200){
                         this.loading = false
                         this.open('成功','添加成功','success')
                         this.$router.push({path:'article',query:{radio1:'审核中'}})
                     } else {
                         this.loading = false
                         this.open('失败','添加失败','warning')
                     }
                 })
                } else {
                    console.log('error submit!!');
                    return false
                }
                } else {
                    this.open('失败','请上传图片','warning')
                }
            })
        },
        //修改添加
        submitFormone(formName){
            this.$refs[formName].validate((valid) => {
              if(this.ruleForm.imgId){
                let Add = {
                        type:this.ruleForm.type,
                        title:this.ruleForm.title,
                        content:this.ruleForm.content,
                        desc:this.ruleForm.desc,
                        weight:this.ruleForm.weight,
                        imgId:this.ruleForm.imgId
                  }
                if (valid) {
                this.loading = true
                 this.$api.information.informationmodification(Add,this.messageid).then(res => {
                     if(res.code === 200){
                         this.loading = false
                         this.open('成功','修改成功','success')
                         this.$router.push(`article?compile=${this.compile}`)
                     } else {
                         this.loading = false
                         this.open('失败','修改失败','warning')
                     }
                 })
                } else {
                    console.log('error submit!!');
                    return false
                }
              } else {
                    this.open('失败','请上传图片','warning')
              }
            })
        },
        open(title,content,type) {
        this.$notify({
          title: title,
          message: content,
          type: type
        });
      },
      goBack(){
        this.$router.push(`article?compile=${this.compile}`)
      }
    }
}
</script>
<style>
    .editarticle{
        width:100%;
    }
    .editarticle .editor {
        line-height: normal !important;
    }
    .editarticle .editor .edit_container  {
        width: 500px;
    } 
    .editarticle .editor .ql-container {
        height: 300px;
    }
    .editarticle .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .editarticle .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .editarticle .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .editarticle .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
</style>
